package com.xydtech.ecard.ecard.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.deepoove.poi.XWPFTemplate;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xydtech.common.annotation.RsaRequest;
import com.xydtech.common.config.XydtechBusiPlatConfig;
import com.xydtech.common.core.domain.entity.SysDept;
import com.xydtech.common.enums.ResultStatus;
import com.xydtech.common.model.ResponseModel;
import com.xydtech.common.utils.DateUtils;
import com.xydtech.common.utils.IdcardUtils;
import com.xydtech.common.utils.StringUtils;
import com.xydtech.common.utils.WordConvertPng;
import com.xydtech.common.utils.http.HttpClientUtil;
import com.xydtech.ecard.ecard.domain.EcardApiMerchantInfo;
import com.xydtech.ecard.ecard.domain.EcardClientInfo;
import com.xydtech.ecard.ecard.domain.EcardPriorCreditRecord;
import com.xydtech.ecard.ecard.domain.EcardPriorCreditTransferRecord;
import com.xydtech.ecard.ecard.service.IEcardApiMerchantInfoService;
import com.xydtech.ecard.ecard.service.IEcardClientInfoService;
import com.xydtech.ecard.ecard.service.IEcardPriorCreditRecordService;
import com.xydtech.ecard.merchant.domain.EcardPriorCreditChart;
import com.xydtech.ecard.merchant.domain.EcardPriorCreditDept;
import com.xydtech.ecard.merchant.domain.EcardPriorCreditUser;
import com.xydtech.ecard.merchant.service.IEcardPriorCreditChartService;
import com.xydtech.ecard.user.domain.EcardApiUserInfo;
import com.xydtech.ecard.user.service.IEcardApiUserService;
import com.xydtech.system.service.ISysConfigService;
import com.xydtech.system.service.ISysDeptService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.io.FileOutputStream;
import java.time.LocalDate;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 电子名片预授信Controller
 *
 * @author xydtech
 * @date 2024-05-16
 */
@Controller
@Slf4j
@Api(tags = "电子名片-预授信管理")
@RequestMapping("/ecardSaasApi/priorCredit")
public class EcardPriorCreditController extends EcardApiBaseController {
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private IEcardApiUserService ecardApiUserService;
    @Autowired
    private IEcardClientInfoService ecardClientInfoService;
    @Autowired
    private IEcardApiMerchantInfoService ecardMerchantInfoService;
    @Autowired
    private IEcardPriorCreditRecordService ecardPriorCreditRecordService;
    @Autowired
    private IEcardPriorCreditChartService ecardPriorCreditChartService;
    @Autowired
    private ISysDeptService sysDeptService;

    /**
     * 启用的配置文件
     */
    @Value("${spring.profiles.active}")
    private String active;

    /**
     * 电子名片-预授信记录列表接口
     *
     * @param: type 1登录人自己数据，2法人机构下全部数据（针对网格管理岗位）
     * @param: search 查询条件
     * @author yjs
     * @date 2024/5/16 16:08
     */
    @PostMapping(value = "/getPriorCreditList")
    @ApiOperation(value = "电子名片-预授信记录列表接口", notes = "电子名片-预授信记录列表接口")
    @ResponseBody
    @RsaRequest
    public ResponseModel getPriorCreditList(@RequestBody String json) {
        try {
            String salt = getSalt();//盐值
            //获取当前用户的信息
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
            JSONObject jsonObject = JSONObject.parseObject(json);
            String type = jsonObject.getString("type");
            String search = jsonObject.getString("search");//查询条件姓名和手机号拆开
            String phone = jsonObject.getString("phone");
            String custType = jsonObject.getString("custType");
            String sts = jsonObject.getString("sts");
            int pageNum = jsonObject.getInteger("pageNum");
            int pageSize = jsonObject.getInteger("pageSize");

            EcardPriorCreditRecord ecardPriorCreditRecord = new EcardPriorCreditRecord();

            if ("1".equals(type)) {
                ecardPriorCreditRecord.setUserId(userInfo.getUserId());
            } else {
                //法人机构信息
                SysDept secondLevelDept = deptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());
                ecardPriorCreditRecord.setDeptId(secondLevelDept.getDeptId());
            }
            ecardPriorCreditRecord.setCustType(custType);
            ecardPriorCreditRecord.setSearch(search);
            ecardPriorCreditRecord.setPhone(phone);
            ecardPriorCreditRecord.setSts(sts);
            PageHelper.startPage(pageNum, pageSize);
            List<EcardPriorCreditRecord> priorCreditRecordList = ecardPriorCreditRecordService.selectEcardPriorCreditRecordList(ecardPriorCreditRecord, salt);
            PageInfo pageInfo = new PageInfo(priorCreditRecordList);
            return ResponseModel.okToJSONArray(pageInfo.getTotal(), priorCreditRecordList);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败,请联系管理员!");
        }
    }

    /**
     * 电子名片-预授信记录详情接口
     *
     * @author yjs
     * @date 2024/5/16 16:08
     */
    @PostMapping(value = "/getPriorCreditInfo")
    @ApiOperation(value = "电子名片-预授信记录详情接口", notes = "电子名片-预授信记录详情接口")
    @ResponseBody
    @RsaRequest
    public ResponseModel getPriorCreditInfo(@RequestBody String json) {
        try {
            String salt = getSalt();//盐值
            JSONObject jsonObject = JSONObject.parseObject(json);
            Long id = jsonObject.getLong("id");
            if (StringUtils.objIsNullOrEmpty(id)) {
                return ResponseModel.error(ResultStatus.PARAMETER_MISSING);
            }

            EcardPriorCreditRecord priorCreditRecordInfo = ecardPriorCreditRecordService.selectEcardPriorCreditRecordById(id, salt);
            return ResponseModel.okToJSON(priorCreditRecordInfo);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败,请联系管理员!");
        }
    }

    /**
     * 电子名片-新增预授信记录接口
     *
     * @author yjs
     * @date 2024/5/16 16:08
     */
    @PostMapping(value = "/addPriorCredit")
    @ApiOperation(value = "电子名片-新增预授信记录接口", notes = "电子名片-新增预授信记录接口")
    @ResponseBody
    @RsaRequest(result = false)
    public ResponseModel addPriorCredit(@RequestBody EcardPriorCreditRecord priorCreditRecordInfo) {
        try {
            String salt = getSalt();//盐值
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
            SysDept dept = sysDeptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());
            //查询预授信年龄区间
            String ageRange = configService.selectConfigByKey("pre_credit_age_range", dept.getDeptId());
            if (ageRange != null) {
                //处理年龄区间，例如20-55
                String[] ageRangeList = ageRange.split("-");
                //根据身份证号获取年龄
                int age = IdcardUtils.getAgeByIdCard(priorCreditRecordInfo.getCardNum());
                if (age <= Integer.valueOf(ageRangeList[0]) || age >= Integer.valueOf(ageRangeList[1])) {
                    return ResponseModel.error("该客户年龄暂不符合本次服务范围，无法进行操作！");
                }
            }

            // 判断启用的配置文件
            if ("yznsh".equals(active)) {
                String url = configService.selectConfigByKey("loan.data.api", dept.getDeptId());
                Map<String, Object> paramMap = new HashMap<>();
                paramMap.put("idNo", priorCreditRecordInfo.getCardNum());
                String days = configService.selectConfigByKey("pre_credit_end_days", dept.getDeptId());
                LocalDate startDate = DateUtils.calculateStartDate(new Date(), Long.valueOf(days));
                paramMap.put("endDate", startDate);
                //查询ods存量客户数据
                String result = HttpClientUtil.doPost(url + "/getstockDataByParams", null, paramMap);
                JSONObject json = JSON.parseObject(result);
                log.info("新增预授信记录接口调获取存量授信信息结果----" + json);
                if ("0".equals(json.getString("code"))) {
                    JSONArray jsonArray = JSON.parseArray(json.getString("data"));
                    if (jsonArray != null && jsonArray.size() > 0) {
                        return ResponseModel.error("该用户已在我行拥有存量授信额度，无法进行操作！");
                    }
                }
            }
            //获取当前用户的信息
            SysDept sysDept = deptService.selectDeptById(userInfo.getDeptId(), salt);
            /**
             * 个人
             * 查询个人客户信息表是否存在数据
             *  存在：验证管护权是否一致，不一致拦截，一致则修改
             *  不存在：新增客户信息表数据
             */
            if ("1".equals(priorCreditRecordInfo.getCustType())) {

                EcardClientInfo infoByCardNum = ecardClientInfoService.getEcardClientInfoByCardNum(priorCreditRecordInfo.getCardNum(), salt);

                if (infoByCardNum != null) {
                    if (!infoByCardNum.getUserId().equals(userInfo.getUserId())) {
                        return ResponseModel.error("保存失败，客户管护权不一致！");
                    }
                    infoByCardNum.setBadgeUrl(priorCreditRecordInfo.getBadgeUrl());
                    infoByCardNum.setHeadUrl(priorCreditRecordInfo.getHeadUrl());
                    ecardClientInfoService.updateEcardClientInfo(infoByCardNum, salt);
                } else {
                    infoByCardNum = new EcardClientInfo();
                    infoByCardNum.setBadgeUrl(priorCreditRecordInfo.getBadgeUrl());
                    infoByCardNum.setHeadUrl(priorCreditRecordInfo.getHeadUrl());
                    infoByCardNum.setCardNum(priorCreditRecordInfo.getCardNum());
                    infoByCardNum.setPhoneNum(priorCreditRecordInfo.getPhone());
                    infoByCardNum.setCname(priorCreditRecordInfo.getName());
                    infoByCardNum.setCreateBy(userInfo.getUserName());
                    infoByCardNum.setUserId(userInfo.getUserId());
                    infoByCardNum.setDeptId(userInfo.getDeptId());
                    ecardClientInfoService.insertEcardClientInfo(infoByCardNum, salt);
                }
                priorCreditRecordInfo.setAssociationId(infoByCardNum.getId());
            }
            /**
             * 个体工商户修改工商户信息表数据
             */
            if ("2".equals(priorCreditRecordInfo.getCustType())) {
                EcardApiMerchantInfo ecardMerchantInfo = new EcardApiMerchantInfo();
                ecardMerchantInfo.setId(priorCreditRecordInfo.getAssociationId());
                ecardMerchantInfo.setLicensePic(priorCreditRecordInfo.getLicensePic());
                ecardMerchantInfoService.addMerchantInfo(ecardMerchantInfo, salt);
            }
            //法人机构信息
            SysDept secondLevelDept = deptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());
            //获取预授信卡模板文件路径
            String preCreditDocx = XydtechBusiPlatConfig.getEcardFilePath() + "/" + secondLevelDept.getDeptId() + "/preCreditTemplate/preCredit.docx";
            /**组装合同模板参数数据*/
            Map<String, Object> datas = new HashMap<>();
            datas.put("cName", priorCreditRecordInfo.getName());
            datas.put("amount", priorCreditRecordInfo.getCarditLimit() + "元");
            datas.put("manager", userInfo.getUserName());
            datas.put("phone", userInfo.getPhoneno());
            datas.put("zhName", secondLevelDept.getDeptName() + sysDept.getDeptName());
            datas.put("data", DateUtils.bigDateTime(new Date()));
            datas.put("address", sysDept.getAddress());
            //生成合同
            XWPFTemplate template = XWPFTemplate.compile(preCreditDocx).render(datas);
            FileOutputStream out;
            String downloadPath = XydtechBusiPlatConfig.getEcardFilePath() + "/" + secondLevelDept.getDeptId() + "/preCreditTemplate/preCreditTest.docx";
            out = new FileOutputStream(downloadPath);
            template.write(out);
            out.flush();
            out.close();
            template.close();
            String pngPath = XydtechBusiPlatConfig.getEcardFilePath() + "/" + userInfo.getDeptId() + "/" + userInfo.getUserId() + "/preCredit/" + priorCreditRecordInfo.getCardNum() + "/" + DateUtils.dateTimeNow() + ".png";
            File file = new File(pngPath);
            File fileParent = file.getParentFile();
            if (!fileParent.exists()) {
                fileParent.mkdirs();
            }
            //word转png
            WordConvertPng.turnPng(downloadPath, pngPath);
            priorCreditRecordInfo.setDeptId(userInfo.getDeptId());
            priorCreditRecordInfo.setCreateBy(userInfo.getUserName());
            priorCreditRecordInfo.setUserId(userInfo.getUserId());
            priorCreditRecordInfo.setPreCreditUrl(pngPath.replaceAll(XydtechBusiPlatConfig.getProfile(), "/profile"));
            int id = ecardPriorCreditRecordService.insertEcardPriorCreditRecord(priorCreditRecordInfo, salt);
            return id > 0 ? ResponseModel.ok(pngPath.replaceAll(XydtechBusiPlatConfig.getProfile(), "/profile")) : ResponseModel.error("添加失败！");
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败,请联系管理员!");
        }

    }

    /**
     * 电子名片-删除预授信记录接口，只作废不删除
     *
     * @author yjs
     * @date 2023/7/26 10:48
     */
    @PostMapping(value = "/delectPriorCredit")
    @ApiOperation(value = "电子名片-删除预授信记录接口", notes = "电子名片-删除预授信记录接口")
    @ResponseBody
    @RsaRequest(result = false)
    public ResponseModel disusePreCreditSts(@RequestBody String json) {
        try {
            String salt = getSalt();//盐值
            JSONObject jsonObject = JSONObject.parseObject(json);
            Long id = jsonObject.getLong("id");
            if (StringUtils.objIsNullOrEmpty(id)) {
                return ResponseModel.error(ResultStatus.PARAMETER_MISSING);
            }
            //获取当前用户的信息
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
            EcardPriorCreditRecord priorCreditRecord = ecardPriorCreditRecordService.selectEcardPriorCreditRecordById(id, salt);
            if (!priorCreditRecord.getUserId().equals(userInfo.getUserId())) {
                return ResponseModel.error("操作失败，管护权信息不一致！");

            }
            int delectCount = ecardPriorCreditRecordService.disusePreCreditSts(id);
            return delectCount > 0 ? ResponseModel.ok() : ResponseModel.error("操作失败！");
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败,请联系管理员!");
        }
    }

    /**
     * 电子名片-转交预授信记录接口
     *
     * @author yjs
     * @date 2023/7/26 10:48
     */
    @PostMapping(value = "/addTransferPriorCredit")
    @ApiOperation(value = "电子名片-转交预授信记录接口", notes = "电子名片-转交预授信记录接口")
    @ResponseBody
    @RsaRequest(result = false)
    public ResponseModel addTransferPriorCredit(@RequestBody EcardPriorCreditTransferRecord priorCreditTransferRecord) {
        try {
            String salt = getSalt();//盐值
            //获取当前用户的信息
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
            EcardPriorCreditRecord priorCreditRecord = ecardPriorCreditRecordService.selectEcardPriorCreditRecordById(priorCreditTransferRecord.getPriorCreditId(), salt);
            if (!priorCreditRecord.getUserId().equals(userInfo.getUserId())) {
                return ResponseModel.error("操作失败，管护权信息不一致！");

            }
            //当前登录人userId
            priorCreditTransferRecord.setTransferId(userInfo.getUserId());
            priorCreditTransferRecord.setTransferDeptId(userInfo.getDeptId());

            //获取接收人的用户信息
            EcardApiUserInfo recipients = ecardApiUserService.getUserInfo(priorCreditTransferRecord.getRecipientId().toString(), salt);
            priorCreditTransferRecord.setRecipientId(recipients.getUserId());
            priorCreditTransferRecord.setRecipientDeptId(recipients.getDeptId());
            int updateCount = ecardPriorCreditRecordService.addTransferPriorCredit(priorCreditTransferRecord);
            return updateCount > 0 ? ResponseModel.ok() : ResponseModel.error("转交失败！");
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败,请联系管理员!");
        }
    }

    /**
     * 验证授信记录
     *
     * @param json
     * @return
     */
    @PostMapping(value = "/verifyCreditRecords")
    @ApiOperation(value = "电子名片-验证授信记录接口", notes = "电子名片-验证授信记录接口")
    @ResponseBody
    @RsaRequest(result = false)
    public ResponseModel verifyCreditRecords(@RequestBody String json) {
        try {
            String salt = getSalt();//盐值
            JSONObject jsonObject = JSONObject.parseObject(json);
            String search = jsonObject.getString("search");//查询条件姓名和手机号拆开
            String custType = jsonObject.getString("custType");
            if (StringUtils.objIsNullOrEmpty(search) || StringUtils.objIsNullOrEmpty(custType)) {
                return ResponseModel.error(ResultStatus.PARAMETER_MISSING);
            }
            //判断客户类型-个人
            if ("1".equals(custType)) {
                EcardPriorCreditRecord priorCreditRecordInfo = new EcardPriorCreditRecord();
                priorCreditRecordInfo.setSts("1");
                priorCreditRecordInfo.setCardNum(search);
                List<EcardPriorCreditRecord> recordList = ecardPriorCreditRecordService.selectEcardPriorCreditRecordList(priorCreditRecordInfo, salt);
                if (recordList != null && recordList.size() > 0) {
                    return ResponseModel.error("该用户已存在预授信，保存后将作废之前数据，是否继续？");
                }
            }
            //判断客户类型-个体工商户
            if ("2".equals(custType)) {
                EcardPriorCreditRecord priorCreditRecordInfo = new EcardPriorCreditRecord();
                priorCreditRecordInfo.setSts("1");
                priorCreditRecordInfo.setAssociationId(Long.valueOf(search));
                List<EcardPriorCreditRecord> recordList = ecardPriorCreditRecordService.selectEcardPriorCreditRecordList(priorCreditRecordInfo, salt);
                if (recordList != null && recordList.size() > 0) {
                    return ResponseModel.error("该商户已存在预授信，保存后将作废之前数据，是否继续？");
                }
            }

            return ResponseModel.ok();
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败,请联系管理员!");
        }
    }

    /**
     * 获取预授信日期接口
     *
     * @return
     */
    @PostMapping(value = "/getPreCreditDate")
    @ApiOperation(value = "电子名片-获取预授信日期接口", notes = "电子名片-获取预授信日期接口")
    @ResponseBody
    @RsaRequest(param = false)
    public ResponseModel getPreCreditDate() {
        try {
            String salt = getSalt();//盐值
            JSONObject jsonObject = new JSONObject();
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
            SysDept dept = sysDeptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());
            // 获取预授信期限
            String term = configService.selectConfigByKey("pre_credit_term", dept.getDeptId());
            jsonObject.put("term", term);
            //开始日期
            String beginDay = DateUtils.parseDateToStr("yyyy-MM-dd", new Date());
            jsonObject.put("beginDay", beginDay);
            //截止日期
            String[] dateArry = DateUtils.parseDateToStr("yyyy-MM-dd", new Date()).split("-");
            String endDay = Integer.valueOf(dateArry[0]) + Integer.valueOf(term) + "-" + dateArry[1] + "-" + dateArry[2];
            jsonObject.put("endDate", endDay);
            return ResponseModel.okToJSON(jsonObject);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败,请联系管理员!");
        }
    }

    /**
     * 电子名片-个人预授信额度统计信息接口
     *
     * @author yuzhiguo
     * @date 2024/5/31 上午9:48
     */
    @PostMapping(value = "/getPriorCreditLimit")
    @ApiOperation(value = "电子名片-个人预授信额度统计信息接口", notes = "电子名片-个人预授信额度统计信息接口")
    @ResponseBody
    @RsaRequest(param = false)
    public ResponseModel getPriorCreditLimit() {
        try {
            String salt = getSalt();//盐值
            //获取当前用户的信息
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
            JSONObject jsonObject = ecardPriorCreditChartService.getPriorCreditLimitStatistics(userInfo.getUserId());
            EcardPriorCreditChart priorCreditChart = (EcardPriorCreditChart) jsonObject.get("priorCreditStatistics");
            if (priorCreditChart.getComparePriorCreditLimit() >= 0){
                priorCreditChart.setCompareType("1");//较上月类型（1：上升，2：下降）
            } else {
                priorCreditChart.setCompareType("2");//较上月类型（1：上升，2：下降）
            }
            return ResponseModel.okToJSON(priorCreditChart);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败,请联系管理员!");
        }
    }

    /**
     * 电子名片-个人预授信户数统计信息接口
     *
     * @author yuzhiguo
     * @date 2024/5/31 上午10:10
     */
    @PostMapping(value = "/getPriorCreditNum")
    @ApiOperation(value = "电子名片-个人预授信户数统计信息接口", notes = "电子名片-个人预授信户数统计信息接口")
    @ResponseBody
    @RsaRequest(param = false)
    public ResponseModel getPriorCreditNum() {
        try {
            String salt = getSalt();//盐值
            //获取当前用户的信息
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
            JSONObject jsonObject = ecardPriorCreditChartService.getPriorCreditNumStatistics(userInfo.getUserId());
            EcardPriorCreditChart priorCreditChart = (EcardPriorCreditChart) jsonObject.get("priorCreditNumStatistics");
            if (priorCreditChart.getComparePriorCreditNum() >= 0){
                priorCreditChart.setCompareType("1");//较上月类型（1：上升，2：下降）
            } else {
                priorCreditChart.setCompareType("2");//较上月类型（1：上升，2：下降）
            }
            return ResponseModel.okToJSON(priorCreditChart);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败,请联系管理员!");
        }
    }

    /**
     * 电子名片-全行预授信额度统计信息
     *
     * @author yuzhiguo
     * @date 2024/5/31 上午10:50
     */
    @PostMapping(value = "/getAllPriorCreditLimit")
    @ApiOperation(value = "电子名片-全行预授信额度统计信息", notes = "电子名片-全行预授信额度统计信息")
    @ResponseBody
    @RsaRequest(param = false)
    public ResponseModel getAllPriorCreditLimit() {
        try {
            String salt = getSalt();//盐值
            //获取当前用户的信息
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
            JSONObject jsonObject = ecardPriorCreditChartService.getAllPriorCreditLimit(userInfo.getDeptId());
            EcardPriorCreditChart priorCreditChart = (EcardPriorCreditChart) jsonObject.get("allPriorCreditLimit");
            if (priorCreditChart.getComparePriorCreditLimit() >= 0){
                priorCreditChart.setCompareType("1");//较上月类型（1：上升，2：下降）
            } else {
                priorCreditChart.setCompareType("2");//较上月类型（1：上升，2：下降）
            }
            return ResponseModel.okToJSON(priorCreditChart);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败,请联系管理员!");
        }
    }

    /**
     * 电子名片-全行预授信户数统计信息
     *
     * @author yuzhiguo
     * @date 2024/5/31 上午11:06
     */
    @PostMapping(value = "/getAllPriorCreditNum")
    @ApiOperation(value = "电子名片-全行预授信户数统计信息", notes = "电子名片-全行预授信户数统计信息")
    @ResponseBody
    @RsaRequest(param = false)
    public ResponseModel getAllPriorCreditNum() {
        try {
            String salt = getSalt();//盐值
            //获取当前用户的信息
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
            JSONObject jsonObject = ecardPriorCreditChartService.getAllPriorCreditNum(userInfo.getDeptId());
            EcardPriorCreditChart priorCreditChart = (EcardPriorCreditChart) jsonObject.get("allPriorCreditNum");
            if (priorCreditChart.getComparePriorCreditNum() >= 0){
                priorCreditChart.setCompareType("1");//较上月类型（1：上升，2：下降）
            } else {
                priorCreditChart.setCompareType("2");//较上月类型（1：上升，2：下降）
            }
            return ResponseModel.okToJSON(priorCreditChart);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败,请联系管理员!");
        }
    }

    /**
     * 电子名片-查询额度折线图数据
     *
     * @author yuzhiguo
     * @date 2024/5/31 上午11:26
     */
    @PostMapping(value = "/getLimitLineChart")
    @ApiOperation(value = "电子名片-查询额度折线图数据", notes = "电子名片-查询额度折线图数据")
    @ResponseBody
    @RsaRequest(param = false)
    public ResponseModel getLimitLineChart() {
        log.info("接口请求时间-------" + DateUtils.getTime());
        try {
            String salt = getSalt();//盐值
            //获取当前用户的信息
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
            List<EcardPriorCreditChart> ecardPriorCreditChartList = ecardPriorCreditChartService.getLimitLineChartByApplet(userInfo.getDeptId());
            log.info("接口返回时间-------" + DateUtils.getTime());
            return ResponseModel.okToJSONArray(ecardPriorCreditChartList);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败,请联系管理员!");
        }
    }

    /**
     * 电子名片-查询户数柱状图数据
     *
     * @author yuzhiguo
     * @date 2024/5/31 上午11:30
     */
    @PostMapping(value = "/getNumLineChart")
    @ApiOperation(value = "电子名片-查询户数柱状图数据", notes = "电子名片-查询户数柱状图数据")
    @ResponseBody
    @RsaRequest(param = false)
    public ResponseModel getNumLineChart() {
        try {
            String salt = getSalt();//盐值
            //获取当前用户的信息
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
            List<EcardPriorCreditChart> ecardPriorCreditChartList = ecardPriorCreditChartService.getNumLineChartByApplet(userInfo.getDeptId());
            return ResponseModel.okToJSONArray(ecardPriorCreditChartList);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败,请联系管理员!");
        }
    }

    /**
     * 电子名片-各机构预授信业务排名
     *
     * @author yuzhiguo
     * @date 2024/6/4 下午1:23
     */
    @PostMapping(value = "/getDeptPriorCreditList")
    @ApiOperation(value = "电子名片-各机构预授信业务排名", notes = "电子名片-各机构预授信业务排名")
    @ResponseBody
    @RsaRequest(param = true, result = true)
    public ResponseModel getDeptPriorCreditList(@RequestBody String json) {
        try {
            String salt = getSalt();//盐值
            //获取当前用户的信息
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
            JSONObject jsonObject = JSONObject.parseObject(json);
            String custType = jsonObject.getString("custType");//客户类型，0全部，1个人，2商户
            int pageNum = jsonObject.getInteger("pageNum");
            int pageSize = jsonObject.getInteger("pageSize");
            EcardPriorCreditDept ecardPriorCreditDept = new EcardPriorCreditDept();
            ecardPriorCreditDept.setDeptId(userInfo.getDeptId());
            if (!"0".equals(custType)){
                ecardPriorCreditDept.setCustType(custType);
            }
            SysDept sysDept = sysDeptService.selectSecondLevelDeptByDeptId(ecardPriorCreditDept.getDeptId());//获取县级机构
            ecardPriorCreditDept.setDeptId(sysDept.getDeptId());
            PageHelper.startPage(pageNum, pageSize);
            List<EcardPriorCreditDept> ecardPriorCreditDeptList = ecardPriorCreditChartService.getDeptPriorCreditListByApplet(ecardPriorCreditDept);
            for (EcardPriorCreditDept priorCreditDept : ecardPriorCreditDeptList) {
                if (priorCreditDept.getComparePriorCreditLimit() >= 0){
                    priorCreditDept.setCompareType("1");//较上月类型（1：上升，2：下降）
                } else {
                    priorCreditDept.setCompareType("2");//较上月类型（1：上升，2：下降）
                }
            }
            PageInfo pageInfo = new PageInfo(ecardPriorCreditDeptList);
            return ResponseModel.okToJSONArray(pageInfo.getTotal(), ecardPriorCreditDeptList);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败,请联系管理员!");
        }
    }

    /**
     * 电子名片-各营销人员预授信业务排名
     *
     * @author yuzhiguo
     * @date 2024/6/4 下午3:36
     */
    @PostMapping(value = "/getUserPriorCreditList")
    @ApiOperation(value = "电子名片-各营销人员预授信业务排名", notes = "电子名片-各营销人员预授信业务排名")
    @ResponseBody
    @RsaRequest(param = true, result = true)
    public ResponseModel getUserPriorCreditList(@RequestBody String json) {
        try {
            String salt = getSalt();//盐值
            //获取当前用户的信息
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
            JSONObject jsonObject = JSONObject.parseObject(json);
            String custType = jsonObject.getString("custType");//客户类型，0全部，1个人，2商户
            int pageNum = jsonObject.getInteger("pageNum");
            int pageSize = jsonObject.getInteger("pageSize");
            EcardPriorCreditUser ecardPriorCreditUser = new EcardPriorCreditUser();
            ecardPriorCreditUser.setDeptId(userInfo.getDeptId());
            if (!"0".equals(custType)){
                ecardPriorCreditUser.setCustType(custType);
            }
            SysDept sysDept = sysDeptService.selectSecondLevelDeptByDeptId(ecardPriorCreditUser.getDeptId());//获取县级机构
            ecardPriorCreditUser.setDeptId(sysDept.getDeptId());
            PageHelper.startPage(pageNum, pageSize);
            List<EcardPriorCreditUser> ecardPriorCreditUserList = ecardPriorCreditChartService.getUserPriorCreditListByApplet(ecardPriorCreditUser);
            for (EcardPriorCreditUser priorCreditUser : ecardPriorCreditUserList) {
                if (priorCreditUser.getComparePriorCreditLimit() >= 0){
                    priorCreditUser.setCompareType("1");//较上月类型（1：上升，2：下降）
                } else {
                    priorCreditUser.setCompareType("2");//较上月类型（1：上升，2：下降）
                }
            }
            PageInfo pageInfo = new PageInfo(ecardPriorCreditUserList);
            return ResponseModel.okToJSONArray(pageInfo.getTotal(), ecardPriorCreditUserList);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败,请联系管理员!");
        }
    }
}
